package com.example.writting.ui.wordfill.adapters

import android.graphics.Typeface
import android.text.SpannableString
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.writting.R
import com.example.writting.databinding.ItemWordComparisonBinding
import com.example.writting.model.WordComparison

class WordComparisonAdapter : RecyclerView.Adapter<WordComparisonAdapter.ViewHolder>() {
    private var items = listOf<WordComparison>()

    fun updateItems(newItems: List<WordComparison>) {
        items = newItems
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemWordComparisonBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items[position])
    }

    override fun getItemCount() = items.size

    class ViewHolder(private val binding: ItemWordComparisonBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: WordComparison) {
            binding.comparisonsLayout.removeAllViews()
            
            item.comparisons.forEach { (word, explanation) ->
                val textView = LayoutInflater.from(binding.root.context)
                    .inflate(android.R.layout.simple_list_item_1, binding.comparisonsLayout, false)
                    .findViewById<TextView>(android.R.id.text1).apply {
                        setTextColor(ContextCompat.getColor(context, R.color.text_primary))
                        setPadding(0, 4.dp, 0, 4.dp)
                    }

                // 创建带有加粗效果的文本
                val text = if (explanation.isNotEmpty()) {
                    "$word：$explanation"
                } else {
                    word
                }
                val spannableString = SpannableString(text)
                spannableString.setSpan(
                    StyleSpan(Typeface.BOLD),
                    0,
                    word.length,
                    SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                
                textView.text = spannableString
                binding.comparisonsLayout.addView(textView)
            }
        }

        private val Int.dp: Int
            get() = (this * binding.root.context.resources.displayMetrics.density).toInt()
    }
} 